from typing import Optional, List

from fastapi import APIRouter, Query, Body

from server.app.cloud_ide.schema.tenant.request.tenant_create_request import TenantCreateRequest
from server.app.cloud_ide.schema.tenant.request.tenant_update_request import TenantUpdateRequest
from server.app.cloud_ide.schema.tenant.response.tenent_info_response import TenantInfoResponse
from server.app.cloud_ide.service.tenant_service import TenantService
from server.framework.core.http_schemas import CommonResponseSchema, TableResponseSchema
from server.framework.core.schemas import OptionsSchema

tenant_api = APIRouter()
tenant_service = TenantService()


@tenant_api.get("/list", response_model=TableResponseSchema, name='获取租户列表')
async def list(current: Optional[int] = Query(1, description='当前页数'),
               page_size: Optional[int] = Query(10, description='每页记录的数量', alias='pageSize')) -> TableResponseSchema:
    results = tenant_service.list_tenant()
    return TableResponseSchema(data=results[current - 1:current * page_size], total=len(results), page=page_size,
                               success=True)


@tenant_api.get("/delete", response_model=CommonResponseSchema, name='删除租户')
async def delete(
        ids: str = Query(None, description='租户id，多条记录以逗号分割')) -> CommonResponseSchema:
    id_list = ids.split(',')
    result = tenant_service.delete_tenant(id_list)
    if result:
        return CommonResponseSchema(data={}, message=f'删除成功', success=True)
    else:
        return CommonResponseSchema(data={}, message=f'删除失败', success=False)


@tenant_api.post("/create", response_model=CommonResponseSchema, name='创建租户')
async def create(data: TenantCreateRequest = Body(None, description='租户创建实体')) -> CommonResponseSchema:
    result = tenant_service.create_tenant(data)
    if result:
        return CommonResponseSchema(data={}, message=f'创建成功', success=True)
    else:
        return CommonResponseSchema(data={}, message=f'创建失败', success=False)


@tenant_api.post("/edit", response_model=CommonResponseSchema, name='更新租户')
async def edit(data: TenantUpdateRequest = Body(None, description='租户更新实体')) -> CommonResponseSchema:
    result = tenant_service.update_tenant(data)
    if result:
        return CommonResponseSchema(data={}, message=f'更新成功', success=True)
    else:
        return CommonResponseSchema(data={}, message=f'更新失败', success=False)


@tenant_api.get("/get_tenant_options", name='获取租户的下拉选项')
async def get_ide_environment_options() -> List[OptionsSchema]:
    tenants = tenant_service.get_all_tenants()
    option_results: List[OptionsSchema] = []
    for tenant in tenants:
        option_results.append(OptionsSchema(value=tenant['id'], label=tenant['name']))
    return option_results


@tenant_api.get("/get_entity", name='获取租户实体')
async def get_entity(id: str = Query(None, description='租户id')) -> TenantInfoResponse:
    entity = tenant_service.get_tenant_info(id)
    return entity
